package band.wukong.practice.webservice.kh.sample04;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @author wukong(wukonggg@139.com)
 */
public class JAXPSampleOfDomAndXPathAPI {

    public static void main(String[] args) throws Exception {
        updateByDom();
    }

    public static void read() throws Exception {
        InputStream is = prepearInputStream();

        // 创建文档处理对象
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // 通过DocumentBuilder创建doc的文档对象
        Document doc = builder.parse(is);
        // 创建XPath
        XPath xPath = XPathFactory.newInstance().newXPath();
        // 找category为web的所有的书的名称
        NodeList list = (NodeList) xPath.evaluate("//book[@category='WEB']"
            , doc, XPathConstants.NODESET);

        for (int i = 0; i < list.getLength(); i++) {
            Element e = (Element) list.item(i);
            System.out.println(e.getElementsByTagName("title").item(0).getTextContent());
        }
    }


    public static void updateByDom() throws Exception {
        InputStream is = prepearInputStream();

        // 创建文档处理对象
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // 通过DocumentBuilder创建doc的文档对象
        Document doc = builder.parse(is);
        // 创建XPath
        XPath xPath = XPathFactory.newInstance().newXPath();
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        // 获取节点
        NodeList list = (NodeList) xPath.evaluate("//book[title='Learning XML']", doc, XPathConstants.NODESET);
        Element bookElmt = (Element) list.item(0);
        Element priceElmt = (Element)bookElmt.getElementsByTagName("price").item(0);
        // 修改节点
        priceElmt.setTextContent("666.66");
        trans.transform(new DOMSource(doc), new StreamResult(System.out));
    }

    private static InputStream prepearInputStream() {
        final String xmlPath = "./src/main/java/band/wukong/practice/webservice/kh/sample04/books.xml";
        InputStream is = null;
        try {
            is = new FileInputStream(new File(xmlPath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.exit(-1);
        }
        return is;
    }
}
